import Schema from 'validate'
const mobileRules=new Schema({
  mobile:{
    type:String,
    required: true,
    match:/^1[3-9]\d{9}$/,
    message:'手机号不合法'
  }
})
const codeRules=new Schema({
  code:{
    type:String,
    required: true,
    match:/^\d{6}$/,
    message:'验证码不合法'
  }
})
Page({
  onLoad({redirector}){
    this.redirector=redirector
  },
  data: {
    countDownVisible: false,//是否开启倒计时
    mobile:'17673867300',   //手机号
    code:''                 //验证码
  },
  // 获取验证码
  async getCode(){
    let {mobile}=this.data
    //手机号验证
    const errs = mobileRules.validate({mobile:mobile})
    if(errs.length){
      return wx.utils.toast(errs[0].message)
    }
    await wx.http({
      url:'/code',
      data:{mobile}
    })
    wx.utils.toast('发送成功，请查收短信')
    // 开启倒计时
    this.setData({
      countDownVisible:true
    })
  },
  //登陆
  async login(){
    let {mobile,code}=this.data
    //手机号验证
    const mobileErrs = mobileRules.validate({mobile:mobile})
    if(mobileErrs.length){
      return wx.utils.toast(mobileErrs[0].message)
    }
    const codeErrs = codeRules.validate({code:code})
    if(codeErrs.length){
      return wx.utils.toast(codeErrs[0].message)
    }
    let res=await wx.http({
      url:'/login',
      method:'post',
      data:{
        mobile,
        code
      }
    })
    if(res.code!==10000)return wx.utils.toast(res.message)
    let app=getApp();
    app.setToken(res.data.token,res.data.refreshToken)
    wx.utils.toast('登录成功！')
   setTimeout(()=>{
    if(this.redirector){
      wx.reLaunch({
        url: '/'+this.redirector,
      })
    }else{
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
   },500)
      
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
})
